package com.example.mongo.config;

import com.mongodb.MongoClient;
import org.bson.types.Decimal128;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.convert.*;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.lang.NonNull;

import java.math.BigDecimal;
import java.util.Arrays;

@Configuration
public class MongoConfig extends AbstractMongoConfiguration {

    @Override
    public String getDatabaseName() {
        return "data_center";
    }

    @Override
    @Bean
    public MongoClient mongoClient() {
        return new MongoClient("localhost");
    }

    @Bean
    public CustomConversions mongoCustomConversions() {
        return new CustomConversions(Arrays.asList(

                new Converter<BigDecimal, Decimal128>() {

                    @Override
                    public Decimal128 convert(@NonNull BigDecimal source) {
                        return new Decimal128(source);
                    }
                },

                new Converter<Decimal128, BigDecimal>() {

                    @Override
                    public BigDecimal convert(@NonNull Decimal128 source) {
                        return source.bigDecimalValue();
                    }

                }
        ));

    }

    @Bean
    @ConditionalOnMissingBean(MongoConverter.class)
    public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory,
                                                       MongoMappingContext context, BeanFactory beanFactory) {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
        MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver,
                context);
        try {
            mappingConverter
                    .setCustomConversions(mongoCustomConversions());
        }
        catch (NoSuchBeanDefinitionException ex) {
            // Ignore
        }
        return mappingConverter;
    }
}
